import {
	HTTP_REQUEST_URL,
	HEADER,
	TOKENNAME,
	HEADERPARAMS
} from '@/config/app';
import {
	Debounce
} from '@/utils/validate.js'

import store from '@/store'
const wihteToastList = ['/salesman/getParentInfo', '/open/forgotPassword/sendMsm',
	'/open/forgotPassword/changePassword', '/open/getBusinessCardByIdNoToken'
]
import caches from '@/config/caches.js'

// 请求计数器，用于正确管理全局loading状态
let requestCount = 0;
const showGlobalLoading = () => {
	requestCount++;
	if (requestCount === 1) {
		uni.showLoading({
			title: '加载中...',
		})
	}
};
const hideGlobalLoading = () => {
	requestCount--;
	if (requestCount <= 0) {
		requestCount = 0;
		uni.hideLoading();
	}
};

export const _toLogin = (() => {
	// 退出登录并跳转登录页面
	store.commit("SET_LOGOUT");
	uni.reLaunch({
		url: '/pages/user/phone/indexApp'
	})
})
export const toLogin = () => {
	Debounce(_toLogin, 800)
}



/**
 * 发送请求
 */
function baseRequest(url, method, data, {
	noAuth = false,
	noVerify = false
}, params) {
	let Url = HTTP_REQUEST_URL,
		header = HEADER
	if (params != undefined) {
		header = HEADERPARAMS;
	}
	console.log("getRes", url)
	const token = uni.getStorageSync(caches.ACCESS_TOKEN)
	if (!noAuth) {
		//登录过期跳转登录页面
		if (!token && !wihteToastList.some(item => url.indexOf(item) !== -1)) {
			toLogin();
		}
	}
	// TODO customer 客户端 走的 该拦截器
	// console.log(url, 'object :>>客户端接口/customer/', url.indexOf('/customer/'));
	// 业务员进入 客户端页面（列如 业务员可领取礼品 调用客户端接口 需要用客户端token） 接口以/customer/开头的是客户端接口 并且身份是业务员的用户salesman  直接使用客户端的token
	const authority = uni.getStorageSync(caches.AUTHORITY)
	if (url.indexOf('/customer/') !== -1 && authority === 'salesman') {
		const token = uni.getStorageSync(caches.CUSTOMER_TOKEN);
		// console.log(token)
		//  授权手机号 调用接口 根据返回 分析用户是 业务员 还是 客户  不需要token
		if (token) header[TOKENNAME] = `${token}`;
	} else {
		// 正常客户端调用 接口 使用客户端的token
		const token = uni.getStorageSync(caches.ACCESS_TOKEN);
		if (token) header[TOKENNAME] = `${token}`;
	}
	return new Promise((reslove, reject) => {
		showGlobalLoading();
		uni.request({
			url: Url + url,
			method: method || 'GET',
			header: header,
			data: data || {},
			success: (res) => {
				hideGlobalLoading();
				console.log("getRes", res)
				let msg = ''
				if (noVerify) {
					reslove(res.data, res);
				} else if (res.data.code == 200) {
					reslove(res.data, res);
				} else {
					if ([991, 992, 993].indexOf(res.data.code) !== -1) {
						toLogin();
						reject(res.data);
					} else if (res.data.code == 500) {
						msg = res.data.msg || '系统异常'
					} else if (res.data.code == 400) {
						msg = res.data.msg || '参数校验失败'
					} else if (res.data.code == 404) {
						msg = res.data.msg || '没有找到相关数据'
					} else if (res.data.code == 403) {
						msg = res.data.msg || '没有相关权限'
					} else {
						msg = res.data.msg || '系统错误'
					}
					if (!wihteToastList.some(item => item === url)) {
						uni.showToast({
							title: msg,
							icon: 'none'
						})
					}
					reject(msg);
				}
			},
			fail: (msg) => {
				console.log("error", msg)
				hideGlobalLoading();
				reject('请求失败');
			}
		})
	});
}

const request = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
	request[method] = (api, data, opt, params) => baseRequest(api, method, data, opt || {}, params)
});



export default request;